//
//  ComposeViewController.swift
//  XLWB
//
//  Created by 郭亮 on 16/3/19.
//  Copyright © 2016年 gl. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class ComposeViewController: UIViewController {
    
    // MARK:-懒加载属性
    private lazy var titleView: ComposeTitleView = ComposeTitleView()
    private lazy var photoCollectionVc: PhotoCollectionViewController = PhotoCollectionViewController(collectionViewLayout: PhotoCollectionViewLayout())
    
    // MARK:-控件
    @IBOutlet weak var toolBarBottomCons: NSLayoutConstraint!
    @IBOutlet weak var composeTextView: ComposeTextView!
    @IBOutlet weak var toolbar: UIToolbar!
    
    // MARK:-系统回调方法
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置导航栏
        setupNavigationBar()
        
        //监听键盘弹出
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)

    }
    
    deinit {
        //移除通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
        //移除弹框
//        SVProgressHUD.dismiss()
        //取消所有任务
//        AFHTTPSessionManager.

    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        composeTextView.becomeFirstResponder()
    }
}

// MARK:-UI界面
extension ComposeViewController {
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "leftBarButtonItemClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "添加", style: .Plain, target: self, action: "rightBarButtonItemClick")
        navigationItem.rightBarButtonItem?.enabled = false
        //设置titleView
        titleView.frame = CGRectMake(0, 0, 100, 35)
        navigationItem.titleView = titleView
    }
}

// MARK:-事件监听
extension ComposeViewController {
    @objc private func leftBarButtonItemClick() {
    dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func rightBarButtonItemClick() {
        SVProgressHUD.showWithStatus("正在发送微博")
        //拼接参数
        guard let accessToken = UserAccountViewModal.shareInstance.accessToken?.access_token else {
            return
        }
        let status = composeTextView.text
        let parameters = ["access_token": accessToken, "status": status]
        //判断有没有传图片
        let image = photoCollectionVc.images.first ?? nil
        if image == nil {
            //获取urlString
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            //发请求
            NetworkingTolls.shareInstance.request(.RequestStylePost, urlString: urlString, parameters: parameters) { (result, error) -> () in
                if result != nil {
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        SVProgressHUD.showSuccessWithStatus("发布成功")
                    })
                }else {
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        SVProgressHUD.showErrorWithStatus("发布失败")
                    })
                }
            }
        }else {
            //获取urlString
            let urlString = "https://api.weibo.com/2/statuses/upload.json"
            //发请求
            NetworkingTolls.shareInstance.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                //将照片转成数据流
                if let imageData = UIImageJPEGRepresentation(image!, 0.9) {
                    formData.appendPartWithFileData(imageData, name: "pic", fileName: "photo.png", mimeType: "image/png")
                }
                }, progress: nil, success: { (task, result) -> Void in
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        SVProgressHUD.showSuccessWithStatus("发布成功")
                    })
                }, failure: { (task, error) -> Void in
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        SVProgressHUD.showErrorWithStatus("发布失败")
                    })
            })
        }
    }
    
    
    
    @objc private func keyboardWillChangeFrame(note: NSNotification) {
        //设置toolBar底部约束
        let endFrameValue = note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let endFrame = endFrameValue.CGRectValue()
        let duration = note.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval

        let bottomCons = UIScreen.mainScreen().bounds.height - endFrame.origin.y
        
        toolBarBottomCons.constant = bottomCons
        
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    @IBAction func photoPickerBtnClick(sender: AnyObject) {
        //隐藏键盘
        composeTextView.resignFirstResponder()
        addChildViewController(photoCollectionVc)
        
        //添加collectionVC的view
        view.insertSubview(photoCollectionVc.view, belowSubview: toolbar)
        //设置约束
        photoCollectionVc.view.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.bottom.equalTo(0)
            make.height.equalTo(self.view.snp_height).multipliedBy(0.7)
        }
        //执行动画
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
}

// MARK:-textView代理
extension ComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        composeTextView.placeHolderLable.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        composeTextView.resignFirstResponder()
    }


}
